package com.easylinkin.linkappapi.mechanical.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.easylinkin.linkappapi.common.model.RequestModel;
import com.easylinkin.linkappapi.mechanical.entity.Mechanical;
import com.easylinkin.linkappapi.mechanical.service.IMechanicalService;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;


/**
 * 铁路机械表 前端控制器
 *
 * @author xy
 * @since 2025-06-11
 */
@Api(tags = "铁路机械表")
@RestController
@RequestMapping("/mechanical/mechanical")
public class MechanicalController {
    @Autowired
    private IMechanicalService mechanicalService;

    @Resource
    LinkappUserContextProducer linkappUserContextProducer;

    /**
     * 分页列表查询
     *
     * @param requestModel
     * @return
     */
    @ApiOperation(value="分页列表查询", notes="分页列表查询")
    @PostMapping(value = "/listPage")
    public RestMessage queryPageList(@RequestBody RequestModel<Mechanical> requestModel) {
        // Assert.notNull(requestModel,"参数不能为空");
        // Assert.notNull(requestModel.getCustomQueryParams(), "customQueryParams 不能为空");
        Assert.notNull(requestModel.getPage(), "page 不能为空");
        requestModel.getCustomQueryParams().setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
        IPage<Mechanical> pageList = mechanicalService.listPage(requestModel);
        return RestBuilders.successBuilder().data(pageList).build();
    }

    /**
     * 保存
     *
     * @param mechanical
     * @return
     */
    @ApiOperation(value="保存", notes="保存")
    @PostMapping(value = "/save")
    public RestMessage save(@RequestBody Mechanical mechanical) {
        setBase(mechanical);
        //如果当前进场时间大于退场时间，则将退场时间设置成空，并将状态设置成在场
        if (mechanical.getOutTime()!=null  &&mechanical.getEnterTime().after(mechanical.getOutTime())) {
            mechanical.setOutTime(null);
            mechanical.setStatus(0);
        }
        if (mechanical.getId() == null) {
//            mechanical.setEnterTime(new Date());
            mechanicalService.save(mechanical);
        } else {
            mechanicalService.updateById(mechanical);
            //解决出场时间更新失败的问题
            if (mechanical.getOutTime() == null){
                mechanicalService.setOutTimeNull(mechanical.getId());
            }
        }
        return RestBuilders.successBuilder().message("保存成功" ).build();
    }

    /**
     * 设置基本属性
     *
     * @param mechanical
     */
    private void setBase(Mechanical mechanical) {
        mechanical.setModifyTime(new Date());
        mechanical.setModifyId(linkappUserContextProducer.getCurrent().getId());
        //没有id就是新增,有就是编辑
        if (StringUtils.isBlank(mechanical.getId())) {
            mechanical.setCreateId(linkappUserContextProducer.getCurrent().getId());
            mechanical.setCreateTime(new Date());
            mechanical.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
        }
    }

    /**
     * 单个退场
     * @param id
     * @param outTime
     * @return
     */
    @ApiOperation(value="单个退场", notes="单个退场")
    @PostMapping(value = "/singleDeparture")
    public RestMessage singleDeparture(@RequestParam("id") String id, @RequestParam(value = "outTime", required = false) String outTime) {
        Mechanical mechanical = mechanicalService.queryById(id);
        if (mechanical == null) {
            return RestBuilders.errorBuilder().message("未找到对应数据").build();
        }
//        mechanical.setStatus(1);
        mechanical.setOutTime(StringUtils.isNotEmpty(outTime) ? DateUtil.parseDateTime(outTime) : new Date());
        setBase(mechanical);
        mechanicalService.updateById(mechanical);
        return RestBuilders.successBuilder().message("退场成功").build();
    }

    /**
     * 批量退场
     * @param ids
     * @param outTime
     * @return
     */
    @ApiOperation(value="批量退场", notes="批量退场")
    @PostMapping(value = "/batchDeparture")
    public RestMessage batchDeparture(@RequestParam("ids") String ids, @RequestParam(value = "outTime", required = false) String outTime) {
        String[] idArr = ids.split(",");
        for (String id : idArr) {
            Mechanical mechanical = mechanicalService.queryById(id);
            if (mechanical == null) {
                return RestBuilders.errorBuilder().message("未找到对应数据").build();
            }
//            mechanical.setStatus(1);
            mechanical.setOutTime(StrUtil.isNotEmpty(outTime) ? DateUtil.parseDateTime(outTime) : new Date());
            setBase(mechanical);
            mechanicalService.updateById(mechanical);
        }
        return RestBuilders.successBuilder().message("批量退场成功").build();
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @ApiOperation(value="通过id删除", notes="通过id删除")
    @DeleteMapping(value = "/delete")
    public RestMessage delete(@RequestParam("id") String id) {
        mechanicalService.removeById(id);
        return RestBuilders.successBuilder().message("删除成功").build();
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @ApiOperation(value="批量删除", notes="批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public RestMessage deleteBatch(@RequestParam("ids") String ids) {
        this.mechanicalService.removeByIds(Arrays.asList(ids.split(",")));
        return RestBuilders.successBuilder().message("批量删除成功").build();
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value="通过id查询", notes="通过id查询")
    @GetMapping(value = "/queryById")
    public RestMessage queryById(@RequestParam("id") String id) {
        Mechanical mechanical = mechanicalService.queryById(id);
        if(mechanical == null) {
            return RestBuilders.errorBuilder().message("未找到对应数据").build();
        }
        return RestBuilders.successBuilder().data(mechanical).build();
    }

    /**
     * 手动执行退场定时任务
     *
     * @return
     */
    @ApiOperation(value="执行退场操作", notes="手动执行退场定时任务")
    @PutMapping(value = "/doDeparture")
    public RestMessage doDeparture() {
        mechanicalService.doDeparture();
        return RestBuilders.successBuilder().build();
    }
}
